// The root URL for the RESTful services
var rootURL = "http://localhost:8080/Projeto3POD-REST/categoria";

var currentCat;

// Retrieve wine list when application starts 
listAll();

// Nothing to delete in initial application state
$('#btnDelete').hide();

// Register listeners
$('#btnSearch').click(function() {
	search($('#searchKey').val());
	return false;
});

// Trigger search when pressing 'Return' on search key input field
$('#searchKey').keypress(function(e){
	if(e.which == 13) {
		search($('#searchKey').val());
		e.preventDefault();
		return false;
    }
});

$('#btnAdd').click(function() {
	novaCategoria();
	return false;
});

$('#btnSave').click(function() {
	if ($('#catId').val() == '')
		salvarCategoria();
	else
		atualizarCategoria();
	return false;
});

$('#btnDelete').click(function() {
	deletarCategoria();
	return false;
});

$('#categoriaList a').live('click', function() {
	findByNome($(this).data('identity'));
});


/////////////////////////////////////////////////////////////////////////////////////

function search(searchKey) {
	if (searchKey == '') 
		listAll();
	else
		findByNome(searchKey);
}

function novaCategoria() {
	$('#btnDelete').hide();
	currentCat = {};
	renderDetails(currentCat); // Display empty form
}

function listAll() {
	console.log('findAll');
	$.ajax({
		type: 'GET',
		url: rootURL,
		dataType: "json", // data type of response
		//success: renderList
		success: function(data){
			currentCat = data;
			renderDetails(currentCat);
		}
	});
}

function findByNome(searchKey) {
	console.log('findByName: ' + searchKey);
	$.ajax({
		type: 'GET',
		url: rootURL + '/nome/' + searchKey,
		dataType: "json",
		success: renderList 
	});
}

function salvarCategoria() {
	console.log('salvarCategoria');
	$.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: rootURL+'/salvar',
		dataType: "json",
		data: formToJSON(),
		success: function(currentCat, textStatus, jqXHR){
			alert('Categoria criado com sucesso.');
			$('#btnDelete').show();
			$('#catId').val(currentCat.id);
			$('#catNome').val(currentCat.nome);
		},
		error: function(jqXHR, textStatus, errorThrown){
			alert('salvarCategoria error: ' + textStatus);
		}
	});
}

function atualizarCategoria() {
	console.log('atualizarCategoria');
	$.ajax({
		type: 'PUT',
		contentType: 'application/json',
		url: rootURL + '/atualizar',// + $('#catId').val(),
		dataType: "json",
		data: formToJSON(),
		success: function(data, textStatus, jqXHR){
			alert('Categoria atualizada com sucesso');
		},
		error: function(jqXHR, textStatus, errorThrown){
			alert('atualizarCategoria error: ' + textStatus);
		}
	});
}

function deletarCategoria() {
	console.log('deletarCategoria');
	$.ajax({
		type: 'DELETE',
		url: rootURL + '/' + $('#wineId').val(),
		success: function(data, textStatus, jqXHR){
			alert('Categoria deletada com sucesso');
		},
		error: function(jqXHR, textStatus, errorThrown){
			alert('deletarCategoria error');
		}
	});
}

function renderList(data) {
	// JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
	var list = data == null ? [] : (data instanceof Array ? data : [data]);

	$('#categoriaList li').remove();
	$.each(list, function(index, CategoriaFilme) {
		$('#categoriaList').append('<li><a href="#" data-identity="' + CategoriaFilme.id + '">'+CategoriaFilme.name+'</a></li>');
	});
}

function renderDetails(currentCat) {
	$('#catId').val(currentCat.id);
	$('#catName').val(currentCat.name);
}

// Helper function to serialize all the form fields into a JSON string
function formToJSON() {
	var cat = $('#catId').val();
	return JSON.stringify({
		"id": cat == "" ? null : cat, 
		"name": $('#catName').val(), 
		});
}
